﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //取本机的IP
            var hostName = Dns.GetHostName();
            var localhostlps = Dns.GetHostByName(hostName);
            IPAddress IP = localhostlps.AddressList[0];
            txtPort.Text = IP.ToString();

            Control.CheckForIllegalCrossThreadCalls = false;
        }
        #region 监听方法

        private Socket socketSend;
        private Dictionary<string, Socket> distanceSocket = new Dictionary<string, Socket>();

        private void Listen(object o)
        {
            Socket socketWatch = o as Socket;

            while (true)
            {
                //监听
                try
                {
                    //负责跟客户端通信
                    socketSend = socketWatch.Accept();

                    //将远程连接的客户端的IP地址和Socket存入集合中
                    distanceSocket.Add(socketSend.RemoteEndPoint.ToString(), socketSend);

                    //将远程连接客户的IP加入下拉框
                    cbxUsers.Items.Add(socketSend.RemoteEndPoint.ToString());

                    ShowMessage(socketSend.RemoteEndPoint.ToString());

                    ShowMessage(socketSend.RemoteEndPoint.ToString() + ":连接成功！");

                    //开新的线程不停的接受客户端发送的信息
                    Thread th = new Thread(Receive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
                catch (Exception)
                {

                    MessageBox.Show("网络连接错误，请重新连入!");
                }
            }
        }
        private void Receive(object o)
        {

        }

        #endregion 监听方法

        private void ShowMessage(string msgStr)
        {
            txtLog.AppendText(msgStr + "\r\n");
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            try
            {
                Socket socketWath = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress iP = IPAddress.Parse(txtPort.Text);
                //创建端口号对象
                IPEndPoint point = new IPEndPoint(iP, Convert.ToInt32(txtPort.Text));

                //开始监听
                socketWath.Bind(point);
                ShowMessage("监听成功...");
                socketWath.Listen(10);

                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWath);
            }
            catch (Exception)
            {
                MessageBox.Show("网络连接错误，请重新连入!");
            }
        }
    }
}
